#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>

int const maxn = 200;
int const inf = 1 << 29;
char s[maxn];
int len;
int a[maxn][maxn];
int f[maxn][maxn];

void dfs(int x, int y)
{
	if (x > y) return;
	if (x == y) {
		if (s[x] == '(' || s[x] == ')') printf("()");
		if (s[x] == '[' || s[x] == ']') printf("[]");
	} else if (a[x][y] == -2) {
		printf("%c", s[x]);
		dfs(x + 1, y - 1);
		printf("%c", s[y]);
	} else {
		dfs(x, a[x][y]);
		dfs(a[x][y]+1, y);
	}
}

int main()
{
	int T; scanf("%d", &T);
	gets(s);
	for (int ti = 1; ti <= T; ti++) {
		if (ti > 1) printf("\n");
		len = 0;
		gets(s);
		gets(s);
		len = strlen(s);
		for (int i = 0; i < len; i++) {
			f[i][i] = 1;
			a[i][i] = i;
		}
		for (int p = 1; p <= len; p++)
			for (int i = 0; i < len - p; i++) {
				int j = i + p;
				if ((s[i] == '(' && s[j] == ')') || (s[i] == '[' && s[j] == ']')) {
					f[i][j] = (p > 1) ? f[i+1][j-1] : 0;
					a[i][j] = -2;
				} else
					f[i][j] = inf;
				for (int k = i, t; k <= j; k++)
					if ((t = f[i][k] + f[k+1][j]) < f[i][j]) {
						f[i][j] = t;
						a[i][j] = k;
					}
			}
		dfs(0, len - 1);
		printf("\n");
	}
}

